package com.wtwd.device.service.impl;


import com.wtwd.device.dao.PaidServiceMapper;
import com.wtwd.device.model.entity.PaidService;
import com.wtwd.device.service.PaidServiceService;
import com.wtwd.device.service.RedisService;
import com.wtwd.device.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zdl
 * @since 2022-04-01
 */
@Service
public class PaidServiceServiceImpl implements PaidServiceService {

    private static final Logger log = LoggerFactory.getLogger(PaidServiceServiceImpl.class);


    @Resource
    private RedisService redisService;

    @Resource
    private PaidServiceMapper paidServiceMapper;

    @Resource
    private RedisTemplate redisTemplate;

    private long limitNum = 30000;


    @Value("${spring.application.name}")
    private String project;


    @Override
    public boolean intercept(String serviceName) {
        long now = System.currentTimeMillis();
        String dateStr = DateUtils.getDateStr(now, DateUtils.dateFormat5);
        String nums = (String) redisTemplate.boundHashOps(project + serviceName).get(dateStr);
        int num = nums == null ? 0 : Integer.parseInt(nums);
        if (num >= limitNum) {
            return false;
        }
        return true;
    }

    @Override
    public void add(String serviceName) {
        long now = System.currentTimeMillis();
        String dateStr = DateUtils.getDateStr(now, DateUtils.dateFormat5);
        String key = project + serviceName;
        long increment = redisTemplate.boundHashOps(key).increment(dateStr, 1);
        if (increment == 1) {
            //记录以往 付费服务调用次数
            Map entries = redisTemplate.boundHashOps(key).entries();
            entries.forEach((k, v) -> {
                try {
                    if (!dateStr.equals(k)) {
                        PaidService paidService = new PaidService();
                        paidService.setService(serviceName);
                        paidService.setProject(project);
                        paidService.setNum(new Integer((String) v));
                        paidService.setRecordDate(DateUtils.parse((String) k, DateUtils.dateFormat5));
                        paidServiceMapper.insert(paidService);
                        redisTemplate.boundHashOps(key).delete(k);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }


}
